import React, { useState } from 'react';
import { View, StyleSheet, ScrollView, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import AppHeader from '../components/AppHeader';
import GradientButton from '../components/GradientButton';
import { Colors } from '../constants/colors';
import InputField from '../components/InputField';
import UploadField from '../components/UploadField';
import { mentorService } from '../services';

export default function AddInstructorScreen() {
  const navigation = useNavigation();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    tel: '',
    credentials: '',
    credentialsFiles: '',
    idCard: '',
    idCardFiles: '',
    certificateFiles: '',
  });

  // 表单验证
  const validateForm = () => {
    if (!formData.name.trim()) {
      Alert.alert('錯誤', '請輸入導師姓名');
      return false;
    }
    if (!formData.tel.trim()) {
      Alert.alert('錯誤', '請輸入手機號碼');
      return false;
    }
    if (!formData.credentials.trim()) {
      Alert.alert('錯誤', '請輸入導師資格');
      return false;
    }
    if (!formData.credentialsFiles) {
      Alert.alert('錯誤', '請上傳導師資格文件');
      return false;
    }
    if (!formData.idCard.trim()) {
      Alert.alert('錯誤', '請輸入身份證號碼');
      return false;
    }
    if (!formData.idCardFiles) {
      Alert.alert('錯誤', '請上傳身份證文件');
      return false;
    }
    return true;
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }

    setLoading(true);
    try {
      const result = await mentorService.addMentor({
        name: formData.name.trim(),
        tel: formData.tel.trim(),
        credentials: formData.credentials.trim(),
        credentialsFiles: formData.credentialsFiles,
        idCard: formData.idCard.trim(),
        idCardFiles: formData.idCardFiles,
        certificateFiles: formData.certificateFiles,
      });

      Alert.alert('成功', '導師申請已提交，請等待審核', [
        { text: '確定', onPress: () => navigation.goBack() }
      ]);
    } catch (error: any) {
      console.error('導師添加失敗:', error);
      Alert.alert('錯誤', error.message || '添加導師失敗，請稍後重試');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <AppHeader title="添加導師" showBack />
      
      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        <View style={styles.form}>
          <View style={styles.formGroup}>
            <InputField
              label="姓名 *"
              value={formData.name}
              onChangeText={(text)=>setFormData({...formData, name:text})}
              placeholder="請輸入導師姓名"
              variant="card"
            />
          </View>

          <View style={styles.formGroup}>
            <InputField
              label="手機號碼 *"
              value={formData.tel}
              onChangeText={(text)=>setFormData({...formData, tel:text})}
              placeholder="請輸入手機號碼"
              keyboardType="phone-pad"
              variant="card"
            />
          </View>

          <View style={styles.formGroup}>
            <InputField
              label="導師資格 *"
              value={formData.credentials}
              onChangeText={(text)=>setFormData({...formData, credentials:text})}
              placeholder="請輸入導師資格"
              variant="card"
            />
          </View>

          <View style={styles.formGroup}>
            <UploadField
              label="導師資格文件 *"
              subtitle="例如:教練證書"
              uri={formData.credentialsFiles}
              onUploadComplete={(ossUrl) => setFormData({...formData, credentialsFiles: ossUrl})}
              tipText="上傳導師資格證書"
            />
          </View>

          <View style={styles.formGroup}>
            <InputField
              label="身份證號碼 *"
              value={formData.idCard}
              onChangeText={(text)=>setFormData({...formData, idCard:text})}
              placeholder="請輸入身份證號碼"
              variant="card"
            />
          </View>

          <View style={styles.formGroup}>
            <UploadField
              label="身份證文件 *"
              uri={formData.idCardFiles}
              onUploadComplete={(ossUrl) => setFormData({...formData, idCardFiles: ossUrl})}
              tipText="上傳身份證照片"
            />
          </View>

          <GradientButton
            title={loading ? "提交中..." : "立即添加"}
            onPress={handleSubmit}
            disabled={loading}
            style={styles.submitButton}
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  content: {
    flex: 1,
  },
  form: {
    padding: 24,
  },
  formGroup: {
    marginBottom: 24,
  },
  label: {
    fontSize: 16,
    fontWeight: '600',
    color: Colors.gray[700],
    marginBottom: 8,
  },
  input: {
    borderWidth: 1,
    borderColor: Colors.gray[300],
    borderRadius: 12,
    paddingHorizontal: 16,
    paddingVertical: 12,
    fontSize: 16,
    backgroundColor: Colors.white,
    minHeight: 48, // 确保安卓上有足够的高度
    textAlignVertical: 'center', // 安卓文本垂直居中
  },
  submitButton: {
    marginTop: 32,
  },
});
